package cn.explink.dop.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.explink.dop.dao.OrderDao;
import cn.explink.dop.dao.StorefrontDao;
import cn.explink.dop.entity.vo.OrderVO;
import cn.explink.dop.entity.vo.StorefrontVO;
import cn.explink.dop.enums.OrderPayMethodEnum;
import cn.explink.dop.enums.OrderStatusEnum;
import cn.explink.dop.enums.pub.YesNoEnum;
import cn.explink.dop.gis.GeoCoder;
import cn.explink.dop.gis.GeoPoint;
import cn.explink.eap.core.util.DataUtils;

/**
 * 模拟订单导入服务
 *
 * @author songkaojun 2015年3月21日
 */
@Transactional
@Service("createOrderService")
public class CreateOrderService {

	private static Map<String, Boolean> ADDRESSMAP = new TreeMap<String, Boolean>();

	private static boolean FIRSTINVOKE = true;

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private StorefrontDao storefrontDao;

	public void create() {
		// if (CreateOrderService.FIRSTINVOKE) {
		// List<String> addressList =
		// this.read("src/main/resources/address.txt");
		List<String> addressList = new ArrayList<String>();
		addressList.add("北京市朝阳区垡头翠城C区106");
		addressList.add("北京市朝阳区王四营乡白鹿公园内8号");
		addressList.add("北京市朝阳区广百东路6号院1号楼明政部国家减灾中心");
		addressList.add("北京市朝阳区大柳树官鑫市场和众A厅108号");
		addressList.add("北京市朝阳区南四环东路88号9排");
		addressList.add("北京市海淀区香山路88号北京康寿安医药有限责任公司");
		addressList.add("北京市西城区大外廊营31号");
		addressList.add("北京市朝阳区小红门路312号四川驻京办事处");
		addressList.add("北京市朝阳区小红门肖村红寺村64号");
		addressList.add("北京市朝阳区小红门东马路99号邻");
		addressList.add("北京市朝阳区小红门三台山路甲3号");
		addressList.add("北京市丰台区镇国寺北街6号院8号楼5单元301");
		addressList.add("北京市海淀区西北旺镇黑龙潭路58号四海公寓70室");
		addressList.add("北京市海淀区西二旗领袖新硅谷C区3号楼1门201室");
		addressList.add("北京市海淀区西三旗南店新村12号楼12门01");
		addressList.add("北京市海淀区清河强佑新城优馆甲1号821室北京东方才博企业管理顾问有限公司");
		addressList.add("北京市海淀区永嘉北路6号大唐电信科技股份有限公司运营商事业部");
		addressList.add("北京市海淀区永丰路5号院5号楼北京广利核系统工程有限公司");
		addressList.add("北京市海淀区圆明园西路2号中国农业大学农学楼428");
		// for (String address : addressList) {
		// CreateOrderService.ADDRESSMAP.put(address, Boolean.FALSE);
		// }
		// }
		// CreateOrderService.FIRSTINVOKE = false;

		List<OrderVO> orderList = this.getOrderList(addressList);

		this.ImportOrderList(orderList);
	}

	public List<String> read(String path) throws IOException {
		List<String> addressList = new ArrayList<String>();
		File file = new File(path);
		if (!file.exists() || file.isDirectory()) {
			throw new FileNotFoundException();
		}
		BufferedReader br = new BufferedReader(new FileReader(file));
		String temp = null;
		temp = br.readLine();
		while (null != temp) {
			addressList.add(temp);
			temp = br.readLine();
		}
		br.close();
		return addressList;
	}

	private List<OrderVO> getOrderList(List<String> addressList) {
		List<OrderVO> orderVOList = new ArrayList<OrderVO>();

		Random rd = new Random();
		for (int i = 0; i < 8; i++) {
			int index = rd.nextInt(addressList.size() - 1);

			orderVOList.add(this.getOrderVO(addressList.get(index)));
		}

		return orderVOList;
	}

	private OrderVO getOrderVO(String address) {
		Random rd = new Random();

		OrderVO orderVO = new OrderVO();
		orderVO.setCode(System.currentTimeMillis() + "");
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		orderVO.setOrderName("红烧排骨" + rd.nextInt(100));
		orderVO.setStatus(OrderStatusEnum.NOT_ASSIGN.getValue());
		orderVO.setStatusChangeTime(new Date());
		orderVO.setStatusLog("创建人：XXX 创建时间:" + DataUtils.date2Str(DataUtils.datetimeFormat) + "状态：" + OrderStatusEnum.NOT_ASSIGN.getText());
		orderVO.setTotalPrice(new BigDecimal(new Random().nextDouble() * 100));
		orderVO.setOrderTotalPrice(orderVO.getTotalPrice().add(new BigDecimal("15")));
		orderVO.setTakeMealPrice(orderVO.getTotalPrice());
		orderVO.setDeliveryPrice(new BigDecimal("5"));
		orderVO.setDetail("泡菜^1 ￥6&&& 炸鸡翅^2 ￥16");
		orderVO.setCustName("王五");
		orderVO.setTelephone("15501100318");
		orderVO.setCustAddress(address);
		orderVO.setNote("微辣");
		orderVO.setDeliveryTime(DataUtils.getDate());
		// 从现在起，三小时内的任意半点和整点
		this.setAskSendTime(orderVO, rd);

		if ((rd.nextInt(100) % 2) == 0) {
			orderVO.setPayMethod(OrderPayMethodEnum.CASH_PAYMENT.getValue());
		} else {
			orderVO.setPayMethod(OrderPayMethodEnum.POS_PAYMENT.getValue());
		}
		if ((rd.nextInt(100) % 2) == 0) {
			orderVO.setNeedWarmBox(YesNoEnum.YES.getValue());
		} else {
			orderVO.setNeedWarmBox(YesNoEnum.NO.getValue());
		}
		List<StorefrontVO> storefrontVOList = this.storefrontDao.finds(new StorefrontVO());
		if ((storefrontVOList != null) && (storefrontVOList.size() != 0)) {
			orderVO.setStorefrontEntity(storefrontVOList.get(0));
		}

		return orderVO;

	}

	private void setAskSendTime(OrderVO orderVO, Random rd) {
		Date randomDate = CreateOrderService.randomDate(DataUtils.getDate(), DateUtils.addHours(DataUtils.getDate(), 3));
		if ((rd.nextInt(100) % 2) == 0) {
			randomDate = DateUtils.setMinutes(randomDate, 0);
		} else {
			randomDate = DateUtils.setMinutes(randomDate, 30);
		}
		randomDate = DateUtils.setSeconds(randomDate, 0);
		randomDate = DateUtils.setMilliseconds(randomDate, 0);
		orderVO.setAskSendTime(randomDate);
	}

	private static Date randomDate(Date beginDate, Date endDate) {
		try {
			if (beginDate.getTime() >= endDate.getTime()) {
				return null;
			}
			long date = CreateOrderService.random(beginDate.getTime(), endDate.getTime());

			return new Date(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static long random(long begin, long end) {
		long rtnn = begin + (long) (Math.random() * (end - begin));
		if ((rtnn == begin) || (rtnn == end)) {
			return CreateOrderService.random(begin, end);
		}
		return rtnn;
	}

	/**
	 * 订单批量入库 入库之前进行地理编码操作
	 *
	 * @param orderList
	 */
	public void ImportOrderList(List<OrderVO> orderList) {
		// 订单批量进行地理编码

		for (int i = 0, length = orderList.size(); i < length; i++) {
			OrderVO interOrder = orderList.get(i);
			interOrder.setCustPosition(this.getOrderPosition(interOrder.getCustAddress()));
		}

		// 入库
		this.orderDao.batchSave(orderList);
	}

	private String getOrderPosition(String address) {
		GeoPoint position = GeoCoder.getInstance().getGeoCoder().GetLocationDetails(address);

		if (position == null) {
			return ""; // 地理编码失败，那么返回空字符
		} else {
			return "{\"lng\":" + position.getLng() + ",\"lat\":" + position.getLat() + "}";
		}

	}

}
